module ResourceControllerMixin

  def self.included(base)
    base.before_action :set_resource, only: [:show, :edit, :update, :destroy, :recommend, :unrecommend, :activate, :inactivate, :toggle_active, :logs]
    base.before_action :set_params, only: [:index]
  end

  def create
    @resource = build_resource
    if @resource.save
      redirect_to redirect_to_after_save
    else
      render action: 'new'
    end
  end

  def edit

  end

  def update
    if resource.update(resource_params)
      if request.xhr?
        render nothing: true
      else
        redirect_to redirect_to_after_save
      end
    else
      render 'edit'
    end
  end

  def destroy
    resource.destroy
    render_nothing
  end

  def recommend
    resource.assign_attributes(recommended: true)
    resource.save(validate: false)
    render_nothing
  end

  def unrecommend
    resource.assign_attributes(recommended: false)
    resource.save(validate: false)
    render_nothing
  end

  def activate
    resource.assign_attributes active: true

    if resource.has_attribute?(:activated_at) && resource.activated_at.nil?
      resource.assign_attributes activated_at: Time.now  
    end

    resource.save(validate: false)

    render_nothing
  end

  def inactivate
    resource.assign_attributes(active: false)
    resource.save(validate: false)

    render_nothing
  end

  def toggle_active
    resource.update(active: !resource.active)
    render_nothing
  end

  def logs
    render partial: 'admin/shared/logs_modal',  locals: {resource: resource}
  end

  def set_params
    @query = params[:query]
  end

  def render_nothing
    if request.xhr?
      render nothing: true
    else
      redirect_to :back
    end
  end
end
